package com.heima.search.task;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.search.dto.ApBehaviorEntry;
import com.heima.search.dto.EntryDto;
import com.heima.search.entity.ApUserSearch;
import com.heima.search.feign.BehaviorFeign;
import com.heima.search.service.IApUserSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class TaskAsync {

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Autowired
    private IApUserSearchService iApUserSearchService;

    @Async
    public void saveSearchRecord(EntryDto dto, String keyword) {
        ResponseResult<ApBehaviorEntry> responseResult = behaviorFeign.getEntry(dto);
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApBehaviorEntry entry = responseResult.getData();
            LambdaQueryWrapper<ApUserSearch> query = new LambdaQueryWrapper<>();
                query.eq(ApUserSearch::getEntryId, entry.getId());
                query.eq(ApUserSearch::getKeyword, keyword);
                ApUserSearch userSearch = iApUserSearchService.getOne(query);
                if (userSearch == null) {
                    ApUserSearch apUserSearch = new ApUserSearch();
                    apUserSearch.setEntryId(entry.getId());
                    apUserSearch.setStatus(1);
                    apUserSearch.setKeyword(keyword);
                    apUserSearch.setCreatedTime(new Date());
                    iApUserSearchService.save(apUserSearch);
                }else {
                    if (userSearch.getStatus()==0){
                        userSearch.setStatus(1);
                        iApUserSearchService.updateById(userSearch);
                    }
                }

        }

    }
}
